﻿using System.ComponentModel;
using System.Windows;
using System.Windows.Data;
using nRoute.Behaviors.Interactivity;
using nRoute.Samples.SquareAway.ViewModels;

namespace nRoute.Samples.SquareAway.Behaviors
{
    public class PlayStateCancelHandledAction
        : BindableTriggerAction<FrameworkElement>
    {
        public static readonly DependencyProperty PlayStateProperty =
            DependencyProperty.Register("PlayState", typeof(PlayState), typeof(PlayStateCancelHandledAction),
            new PropertyMetadata(PlayState.Paused, OnPlayStateChanged));

        private bool _cancelNext;

#region Properties

        public PlayState PlayState
        {
            get { return (PlayState)GetValue(PlayStateProperty); }
            set { SetValue(PlayStateProperty, value); }
        }

        public Binding PlayStateBinding
        {
            get { return GetBinding(PlayStateProperty); }
            set { SetBinding<PlayState>(PlayStateProperty, value); }
        }
        
#endregion

#region Overrides

        protected override void Invoke(object parameter)
        {
            var _eventArgs = (CancelEventArgs)parameter;
            _eventArgs.Cancel = _cancelNext;

            // reset for the next time
            _cancelNext = false;
        }

#endregion

#region Handlers

        private void PlayStateUpdate(PlayState? oldState, PlayState newState)
        {
            if (!oldState.HasValue)
            {
                _cancelNext = false;
            }
            else if (newState == ViewModels.PlayState.Paused)
            {
                _cancelNext = true;
            } 
        }

        private static void OnPlayStateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var _oldValue = (PlayState?)e.OldValue;
            var _newValue = (PlayState)e.NewValue;
            ((PlayStateCancelHandledAction)d).PlayStateUpdate(_oldValue, _newValue);           
        }

#endregion

    }
}